#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class String
{
public:
    String()
    : _pstr(new char[1]())
    {
        cout << "String()" << endl;
    }

    String(const char *pstr)
    : _pstr(new char[strlen(pstr) + 1]())
    {
        cout << "String(const char *)" << endl;
        strcpy(_pstr, pstr);
    }

    String(const String & rhs)
    : _pstr(new char[strlen(rhs._pstr) + 1]())
    {
        cout << "String(const String &)" << endl;
        strcpy(_pstr, rhs._pstr);
    }

    String & operator=(const String & rhs)
    {
        cout << "String &operator=(const String &)" << endl;
        if(this != &rhs)
        {
            delete [] _pstr;
            _pstr = new char[strlen(rhs._pstr) + 1]();
            strcpy(_pstr, rhs._pstr);
        }
        return *this;
    }

    size_t length() const
    {
        size_t len = 0;
        if(_pstr)
        {
            len = strlen(_pstr);
        }

        return len;

    }

    const char * c_str() const
    {
        if(_pstr)
        {
            return _pstr;
        }
        else
        {
            return nullptr;
        }
    }


    ~String()
    {
        cout << "~String()" << endl;
        if(_pstr)
        {
            delete [] _pstr;
            _pstr = nullptr;
        }
    }

    void print() const
    {
        if(_pstr)
        {
            cout << "_pstr = " << _pstr << endl;
        }else{
            cout << endl;
        }
    }

private:
    char * _pstr;
};
void test0(){
    int a = 1;
    int b = 2;
    /* &(a + b); */

    //匿名变量、匿名对象不见得一定是右值
    //比如堆上的变量、对象就是左值,持续存活
    //还得根据实际情况分析
    int * p = new int(10);
    cout << p << endl;
    delete p;


    String s1("hello");
    cout << &s1 << endl;

    /* &(String("world")); */

    cout << &"hello" << endl;
    const char * pstr = "hello";
    printf("%p\n",pstr);
}

void test1(){
    int a = 1;
    int b = 2;
    int & ref = a;
    /* int & ref2 = a + b; */
    const int & ref2 = a;
    const int & ref3 = a + b;
    cout << ref3 << endl;

    const String & rhs = String("hello");  
    rhs.print();
    cout << &rhs << endl;
    cout << "over" << endl;


    //右值引用只能绑定右值，不能绑定左值
    int && reff = a + b;
    cout << &reff << endl;
    /* int && reff2 = b; */

    String && rhss = String("world");
    cout << "over again" << endl;

    

}


int main(void){
    test1();
    return 0;
}
